//
//  ViewController.m
//  HappyStore
//
//  Created by 点点充 on 16/1/11.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "ViewController.h"
#import "XTLoopScrollView.h"
#import <MWPhotoBrowser.h>
#import "WXApi.h"
#import <TencentOpenAPI/TencentOAuth.h>
//会员ID
NSString *allConstMemberid;
//会员token
NSString *allConstMemberToken;
//会员类型
NSString *allConstMemberUserType;
//会员地址
NSString *allConstMemberAddress;
//会员头像
NSString *allConstMemberImgStr;


@interface ViewController ()<XTLoopScrollViewDelegate,MWPhotoBrowserDelegate,WBHttpRequestDelegate,TencentSessionDelegate,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UIGestureRecognizerDelegate>
{
    NSMutableArray *photos;
    
    UINavigationController *homeNAV;
    
    TencentOAuth *_tencentOAuth;
    
}
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UIButton *WeChatBtn;
@property (weak, nonatomic) IBOutlet UIView *userIDView;
@property (weak, nonatomic) IBOutlet UIView *passWordView;

@property (weak, nonatomic) NSArray * historyArray;
@end

@implementation ViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = false;
    //判断如果微信没有安装就把这个按钮隐藏了 不然不能上架
    if (![WXApi isWXAppInstalled]) {
        
        _WeChatBtn.hidden = YES;
    }
    
    self.passWordView.layer.masksToBounds = YES;
    self.passWordView.layer.cornerRadius = 5.0f;
    
    self.userIDView.layer.masksToBounds = YES;
    self.userIDView.layer.cornerRadius = 5.0f;
    
    //    _tfUserName.text = @"13752841308";
    //    _tfPassWord.text = @"asdfgh";
    //个人：  cxs123   123456
    //企业：cslcsl   123123
    
    //    _tfUserName.text = @"cxs123";
    //    _tfPassWord.text = @"123456";
    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.rowHeight = 44;
    
    [self readNSUserDefaults];
    
    self.scrollView.delegate = self;
    self.scrollView.scrollEnabled = YES;

    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchScrollView)];
    recognizer.delegate = self;
    [recognizer setNumberOfTapsRequired:1];
    [recognizer setNumberOfTouchesRequired:1];
    [self.scrollView addGestureRecognizer:recognizer];
    
    
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

-(void)touchScrollView{
    
    if (!self.tableview.hidden) {
        self.tableview.hidden = YES;
    }

}
- (void)didLogoutFor:(NSString *)reason {
    NSLog(@"------------reason:%@",reason);
}

- (void)tapingCurrentIndex:(NSInteger)currentIndex andWho:(XTLoopScrollView *)XTLoopScroll
{
    photos = [NSMutableArray array];
    
    // Add photos
    //    [photos addObject:[MWPhoto photoWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"photo2l" ofType:@"jpg"]]]];
    [photos addObject:[MWPhoto photoWithURL:[NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/1350226-2d36c382f013d4b7?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"]]];
    [photos addObject:[MWPhoto photoWithURL:[NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/1350226-ed34820e830b0f49?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"]]];
    
    // Add video with poster photo
    MWPhoto *video = [MWPhoto photoWithURL:[NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/1350226-ab281b7758e803e1?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"]];
    video.videoURL = [[NSURL alloc] initWithString:@"https://scontent.cdninstagram.com/hphotos-xpa1/t50.2886-16/11200303_1440130956287424_1714699187_n.mp4"];
    [photos addObject:video];
    
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    browser.displayNavArrows = YES;
    browser.alwaysShowControls = YES;
    [browser setCurrentPhotoIndex:1];
    // Present
    //    [self.navigationController pushViewController:browser animated:YES];
    [self presentViewController:browser animated:YES completion:nil];
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < photos.count) {
        return [photos objectAtIndex:index];
    }
    return nil;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"开始搜索");
    
    if(textField == self.tfUserName)
    {
    
        if (self.historyArray) {
            self.tableview.hidden = NO;
        }
    
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == _tfUserName) {
        _imgView_UserName.image = [UIImage imageNamed:@"input-selected"];
    }
    
    if (textField == _tfPassWord) {
        _imgView_PassWord.image = [UIImage imageNamed:@"input-selected"];
    }
    
    
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == _tfUserName) {
        _imgView_UserName.image = [UIImage imageNamed:@"input-normal"];
    }
    
    if (textField == _tfPassWord) {
        _imgView_PassWord.image = [UIImage imageNamed:@"input-normal"];
    }
}

#pragma mark - 搜索历史记录
-(void)readNSUserDefaults
{
    self.historyArray = [USER_DEFAULTS arrayForKey:@"searchHistory"];
    [self.tableview reloadData];
}

#pragma mark - tableview dataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.historyArray.count;

}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 44;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString * ID = @"userCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    
    cell.textLabel.font = [UIFont systemFontOfSize:14.0f];
    cell.textLabel.text = self.historyArray[indexPath.row];
    
    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    self.tfUserName.text = self.historyArray[indexPath.row];
    self.tableview.hidden = YES;

}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    UIView * footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.width, 44)];
    footView.backgroundColor = [UIColor whiteColor];
    
    UIButton * clearBtn = [[UIButton alloc]initWithFrame:CGRectMake(tableView.width - 70, 5, 60, 34)];
    [clearBtn setTitle:@"清空记录" forState:0];
    clearBtn.titleLabel.font = [UIFont systemFontOfSize:12.0f];
    [clearBtn setTitleColor:[UIColor lightGrayColor] forState:0];
    [clearBtn addTarget:self action:@selector(clearHistory) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:clearBtn];
    
    return footView;

}

-(void)clearHistory{

    [USER_DEFAULTS removeObjectForKey:@"searchHistory"];
    [USER_DEFAULTS synchronize];
    self.tableview.hidden = YES;

}

#pragma mark - 注册
- (IBAction)btnClickZhuCe:(id)sender
{
    //    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
}

#pragma mark - 登录
- (IBAction)btnClickLogin:(id)sender
{
    BOOL isOk = YES;
    
    if (self.tfUserName.text.length==0) {
        isOk = NO;
        [self showSingleIconBubble:@"请输入账号"];

    }
    
    
    if (isOk && self.tfPassWord.text.length == 0) {
        isOk = NO;
         [self showSingleIconBubble:@"请输入密码"];

    }
    
    
    if (isOk) {
        [self showRoundProgressWithTitle:@"请稍后..."];
        NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:_tfUserName.text forKey:@"login_account"];//登录用户名
        [muDicParameters setObject:_tfPassWord.text forKey:@"password"];//密码
        
        
        NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"login_app_user.im"];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//            NSLog(@"%@",dicInfo);
            
            [self hideBubble];
            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                //"data":[{"phone":"13896438419","email":"","token":"SX8QbfVIl6RAXqwjgUn8","userid":9,"account":"cxs123","usertype":1,"password":"e10adc3949ba59abbe56e057f20f883e"}]
                NSDictionary *dicUserInfo = [dicInfo objectForKey:@"data"][0];

                
                allConstMemberid = dicUserInfo[@"userid"];
                allConstMemberToken = dicUserInfo[@"token"];
                allConstMemberUserType = dicUserInfo[@"usertype"];
                allConstMemberAddress = dicUserInfo[@"address"];
                allConstMemberImgStr = dicUserInfo[@"headPhoto"];
                
                NSMutableArray *searTXT = [NSMutableArray array];
                if (self.historyArray) {
                    searTXT = [self.historyArray mutableCopy];
                }
                
                if (![searTXT containsObject:self.tfUserName.text]) {
                    
                    [searTXT addObject:self.tfUserName.text];
                    
                }
                
                //将返回数据保存到数据库中
                [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
                    //通过用户账号查找得到实体
                    //如果实体不存在，则创建
                   Person * person = [Person MR_findFirstByAttribute:@"account" withValue:_tfUserName.text inContext:localContext];
                    
                    if (!person) {
                        person = [Person MR_createEntityInContext:localContext];
                    }
                    
                    person.token = dicUserInfo[@"token"];
                    person.phone = dicUserInfo[@"phone"];
                    person.userid = [NSString stringWithFormat:@"%@",dicUserInfo[@"userid"]];
                    person.account = [NSString stringWithFormat:@"%@",dicUserInfo[@"account"]];
                    person.userType = [NSString stringWithFormat:@"%@", dicUserInfo[@"userType"]];
                    person.usertype =  [NSString stringWithFormat:@"%@", dicUserInfo[@"usertype"]];
                    person.password = [NSString stringWithFormat:@"%@",_tfPassWord.text];
                    person.authState = [NSString stringWithFormat:@"%@",dicUserInfo[@"authState"]];
                    person.industry = dicUserInfo[@"industry"];
                    person.address = dicUserInfo[@"address"];
                    person.imToken = dicUserInfo[@"imToken"];
                    person.userName = dicUserInfo[@"userName"];
                    
                    UIImageView * img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
                    [img sd_setImageWithURL:[NSURL URLWithString:allConstMemberImgStr]];
                    
                    NSData * imgData = UIImageJPEGRepresentation(img.image, 1.0f);
                    person.headPhoto = imgData;

                    person.vipLevel = [NSString stringWithFormat:@"%@",dicUserInfo[@"vipLevel"] ];

                    
                }
                completion:^(BOOL contextDidSave, NSError *error) {

                                  }];
                
                //获取个人详细信息
                [self startPostNetWork];
                
                //将上述数据全部存储到NSUserDefaults中
                [USER_DEFAULTS setObject:searTXT forKey:@"searchHistory"];
                
                [USER_DEFAULTS setObject:dicUserInfo[@"token"] forKey:@"token"];
                [USER_DEFAULTS setObject:dicUserInfo[@"phone"] forKey:@"phone"];
                [USER_DEFAULTS setObject:dicUserInfo[@"userid"] forKey:@"userid"];
                [USER_DEFAULTS setObject:dicUserInfo[@"account"] forKey:@"account"];
                [USER_DEFAULTS setObject:[NSString stringWithFormat:@"%@",dicUserInfo[@"usertype"]] forKey:@"usertype"];
                [USER_DEFAULTS setObject:_tfPassWord.text forKey:@"password"];
                [USER_DEFAULTS setObject:dicUserInfo[@"industry"] forKey:@"industry"];
                [USER_DEFAULTS setObject:dicUserInfo[@"address"] forKey:@"address"];
                [USER_DEFAULTS setObject:dicUserInfo[@"imToken"] forKey:@"imToken"];
                [USER_DEFAULTS setObject:dicUserInfo[@"userName"] forKey:@"userName"];
                [USER_DEFAULTS setObject:dicUserInfo[@"headPhoto"] forKey:@"headPhoto"];
                [USER_DEFAULTS setObject:dicUserInfo[@"vipLevel"] forKey:@"vipLevel"];
                [USER_DEFAULTS setObject:@"YES" forKey:@"isOpenSound"];
                [LSCoverUserInfo CoverVipType];
                [USER_DEFAULTS synchronize];
                
                [[RCIM sharedRCIM] connectWithToken:dicUserInfo[@"imToken"] success:^(NSString *userId) {
                    NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
                } error:^(RCConnectErrorCode status) {
                    NSLog(@"登陆的错误码为:%ld", (long)status);
                } tokenIncorrect:^{
                    //token过期或者不正确。
                    //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
                    //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
                    NSLog(@"token错误");
                }];
                
                //刷新缓存
                RCUserInfo *userInfo = [RCUserInfo new];
                userInfo.userId = dicUserInfo[@"account"];
                userInfo.name = dicUserInfo[@"userName"];
                userInfo.portraitUri = dicUserInfo[@"headPhoto"];
                [[RCIM sharedRCIM] refreshUserInfoCache:userInfo
                                             withUserId:userInfo.userId];
                

                [self showRightWithTitle:[dicInfo objectForKey:@"msg"] autoCloseTime:2];
                
            }else {
                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:[dicInfo objectForKey:@"msg"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil];
                [alert show];
            }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {


        }];
    }
    
    
    
    
}
#pragma mark - 获取个人详细信息
- (void)startPostNetWork
{
    
    //token=rE3F2m8AvfC7CVh85O9q&userId=9&userType=用户类型 1-个人，2-企业，3-政府
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    [muDicParameters setObject:allConstMemberUserType forKey:@"userType"];//用户类型 1-个人，2-企业，3-政府
    [muDicParameters setObject:allConstMemberid forKey:@"userId"];
    [muDicParameters setObject:allConstMemberToken forKey:@"token"];//验证用户
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"MyBasicMessage_app_myHome.im.lensum"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        
        //        NSLog(@"%@",dicInfo);
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            NSDictionary * dictData = [NSDictionary dictionaryWithDictionary:dicInfo[@"data"]];
            dictData = dicInfo[@"data"];
            
            if ([[USER_DEFAULTS objectForKey:@"token"] isEqualToString:@"1"]) {
                
                [self dismissViewControllerAnimated:YES completion:nil];
            }else {
                
                //去首页
                UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
                UITabBarController *tabBarC = [LoginAndRegister instantiateViewControllerWithIdentifier:@"homeTabBar"];
                [self presentViewController:tabBarC animated:YES completion:nil];
            }

            //将返回数据保存到数据库中
            [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
                
                Person * tmp = [Person MR_findFirstByAttribute:@"userid" withValue:allConstMemberid inContext:localContext];

                    tmp.levelLovertime = dictData[@"levelovertime"];
                    tmp.positionName = dictData[@"positionName"];
                    tmp.companyName = dictData[@"companyName"];
                    tmp.mobile = dictData[@"mobile"];
                    tmp.email = dictData[@"email"];
                    NSLog(@"%@",tmp);

                
            }
                              completion:^(BOOL contextDidSave, NSError *error) {
                                  NSLog(@"=-===%@", (contextDidSave ? @"保存数据成功" : @"保存数据失败"));
                                  
                              }];

        }else {
            
            [self hideBubble];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showSingleIconBubble:error.localizedDescription];
        
    }];
}

/**
 *  @author LLJ, 16-01-19 12:01:49
 *
 *  直接进入
 *
 *  @param sender aaaa
 */
- (IBAction)btnClickGo:(id)sender
{
    if ([[USER_DEFAULTS objectForKey:@"token"] isEqualToString:@"1"]) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else {
        [USER_DEFAULTS setObject:@"1" forKey:@"token"];
        [USER_DEFAULTS synchronize];
        //去首页
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
        UITabBarController *tabBarC = [LoginAndRegister instantiateViewControllerWithIdentifier:@"homeTabBar"];
        [self presentViewController:tabBarC animated:YES completion:nil];
    }
    
    
    
    
}

/**
 *  @author LLJ, 16-01-30 16:01:47
 *
 *  微博登录
 *
 *  @param sender aa
 */
- (IBAction)btnClickWeiBo:(id)sender
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startLogin:) name:@"startOtherLogin" object:nil];
    
    [WeiboSDK enableDebugMode:NO];
    [WeiboSDK registerApp:@"2931462162"];
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"http://www.baidu.com";
    request.scope = @"all";
    request.userInfo = @{@"myKey": @"myValue"};
    [WeiboSDK sendRequest:request];
}

/**
 *  @author LLJ, 16-01-30 16:01:13
 *
 *  微信登录
 *
 *  @param sender
 */
- (IBAction)btnClickWeiCart:(id)sender
{
    
    if ([WXApi isWXAppInstalled]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startLoginWeiChat:) name:@"startLoginWeiChat" object:nil];
        //构造SendAuthReq结构体
        SendAuthReq *req =[[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo" ;
        req.state = @"123" ;
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req];
        
    }else {
        [MRProgressOverlayView showErrorWithStatus:@"您未安装微信!"];

    }
    
    
}

/**
 *  @author LLJ, 16-01-30 16:01:21
 *
 *  QQ登录
 *
 *  @param sender
 */
- (IBAction)btnClickQQ:(id)sender
{
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:@"1104898161" andDelegate:self];
    NSArray *_permissions =  [NSArray arrayWithObjects:@"get_user_info", @"get_simple_userinfo", @"add_t", nil];
    [_tencentOAuth authorize:_permissions];
    
}

- (void)getUserInfoResponse:(APIResponse*) response
{
    NSLog(@"%@",response);
    [MRProgressOverlayView show];
    
    NSMutableDictionary *muDic = [NSMutableDictionary dictionary];
    [muDic setObject:response.jsonResponse[@"nickname"] forKey:@"userName"];
    [muDic setObject:response.jsonResponse[@"figureurl_qq_2"] forKey:@"headPhoto"];
    [muDic setObject:_tencentOAuth.openId forKey:@"threeKey"];
    [muDic setObject:@"0" forKey:@"threeType"];
    [self btnClickOtherLogin:muDic];
}

- (void)tencentDidLogin
{
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        //  记录登录用户的OpenID、Token以及过期时间
        [_tencentOAuth getUserInfo];
    }
    else
    {
        [MRProgressOverlayView showErrorWithStatus:@"登录不成功 没有获取accesstoken"];

    }
    
}

#pragma mark -微博回调
- (void)startLogin:(NSNotification *)dic
{
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionaryWithDictionary:dic.userInfo];//通过这个获取到传递的对象
    
    [MRProgressOverlayView show];
    
    NSMutableDictionary *muDicPare = [NSMutableDictionary dictionary];
    [muDicPare setObject:muDicParameters[@"accessToken"] forKey:@"access_token"];
    [muDicPare setObject:muDicParameters[@"userID"] forKey:@"uid"];
    
    [WBHttpRequest requestWithAccessToken:muDicParameters[@"accessToken"] url:@"https://api.weibo.com/2/users/show.json" httpMethod:@"GET" params:muDicPare delegate:self withTag:@"1"];
    
    [MRProgressOverlayView dismiss];
    
}

- (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data
{
    NSDictionary *dicInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    NSMutableDictionary *muDic = [NSMutableDictionary dictionary];
    [muDic setObject:dicInfo[@"screen_name"] forKey:@"userName"];
    [muDic setObject:dicInfo[@"avatar_large"] forKey:@"headPhoto"];
    NSLog(@"%@",request.params[@"access_token"]);
    [muDic setObject:request.params[@"access_token"] forKey:@"threeKey"];
    [muDic setObject:@"2" forKey:@"threeType"];
    [self btnClickOtherLogin:muDic];
}

//- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error
//{
//
//}

#pragma mark - 微信回调
- (void)startLoginWeiChat:(NSNotification *)dic
{
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionaryWithDictionary:dic.userInfo];//通过这个获取到传递的对象
    [self btnClickOtherLogin:muDicParameters];
}


#pragma mark - 第三方登录
- (void)btnClickOtherLogin:(NSMutableDictionary *)muDicParameters
{
    //headPhoto=头像地址&userName=第三方名称&threeType=第三方类型（0-qq 1-微信 2-微博'）&threeKey=第三方key值
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"threeLogin_app_user.im"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        NSLog(@"%@",dicInfo);
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            //"data":[{"phone":"13896438419","email":"","token":"SX8QbfVIl6RAXqwjgUn8","userid":9,"account":"cxs123","usertype":1,"password":"e10adc3949ba59abbe56e057f20f883e"}]
            NSDictionary *dicUserInfo = [dicInfo objectForKey:@"data"][0];
            
            if ([[USER_DEFAULTS objectForKey:@"token"] isEqualToString:@"1"]) {
                
                [self dismissViewControllerAnimated:YES completion:nil];
                
            }else {
                
                //去首页
                UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
                UITabBarController *tabBarC = [LoginAndRegister instantiateViewControllerWithIdentifier:@"homeTabBar"];
                [self presentViewController:tabBarC animated:YES completion:nil];
            }
            
            [USER_DEFAULTS setObject:muDicParameters[@"userName"] forKey:@"threeUserName"];
            [USER_DEFAULTS setObject:muDicParameters[@"headPhoto"] forKey:@"threeHeadPhoto"];
            [USER_DEFAULTS setObject:muDicParameters[@"threeKey"] forKey:@"threeKey"];
            
            allConstMemberid = dicUserInfo[@"userid"];
            allConstMemberToken = dicUserInfo[@"token"];
            [USER_DEFAULTS setObject:dicUserInfo[@"token"] forKey:@"token"];
            [USER_DEFAULTS setObject:dicUserInfo[@"phone"] forKey:@"phone"];
            [USER_DEFAULTS setObject:dicUserInfo[@"userid"] forKey:@"userid"];
            [USER_DEFAULTS setObject:dicUserInfo[@"account"] forKey:@"account"];
            [USER_DEFAULTS setObject:[NSString stringWithFormat:@"%@",dicUserInfo[@"usertype"]] forKey:@"usertype"];
            [USER_DEFAULTS setObject:dicUserInfo[@"password"] forKey:@"password"];
            [USER_DEFAULTS setObject:dicUserInfo[@"industry"] forKey:@"industry"];
            [USER_DEFAULTS setObject:dicUserInfo[@"address"] forKey:@"address"];
            [USER_DEFAULTS setObject:dicUserInfo[@"imToken"] forKey:@"imToken"];
            [USER_DEFAULTS setObject:dicUserInfo[@"userName"] forKey:@"userName"];
            [USER_DEFAULTS setObject:dicUserInfo[@"headPhoto"] forKey:@"headPhoto"];
            [USER_DEFAULTS setObject:dicUserInfo[@"vipLevel"] forKey:@"vipLevel"];
            [USER_DEFAULTS synchronize];
            
            [[RCIM sharedRCIM] connectWithToken:dicUserInfo[@"imToken"] success:^(NSString *userId) {
                
                //刷新缓存
                RCUserInfo *userInfo = [RCUserInfo new];
                userInfo.userId = userId;
                userInfo.name = dicUserInfo[@"userName"];
                userInfo.portraitUri = dicUserInfo[@"headPhoto"];
                [[RCIM sharedRCIM] refreshUserInfoCache:userInfo
                                             withUserId:userInfo.userId];
                
                NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
            } error:^(RCConnectErrorCode status) {
                NSLog(@"登陆的错误码为:%ld", (long)status);
            } tokenIncorrect:^{
                //token过期或者不正确。
                //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
                //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
                NSLog(@"token错误");
            }];
            
            
            [MRProgressOverlayView showSuccessWithStatus:[dicInfo objectForKey:@"msg"]];
            
            
        }else {
            [MRProgressOverlayView showErrorWithStatus:[dicInfo objectForKey:@"msg"]];
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MRProgressOverlayView showErrorWithStatus:error.localizedDescription];

    }];
    
    
}



@end
